package com.eric.config;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class SaTokenConfigure implements WebMvcConfigurer {
    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handler->{
            SaRouter
                    .match("/**")
//                    对"/login/**"下面的目录不用校验权限密码
                    .notMatch("/login/**")
//                    暂时不拦截文件夹下面的文件访问,记住如果单纯是/file/**，还会拦截的
                    .notMatch("/file/equipPhotos/**","/file/menuIcon/**","/file/profilePhoto/**"
                            ,"/file/equipTransferPhotos/**","/file/materialPhotos/**","/file/materialInPhotos/**"
                    ,"/file/materialOutPhotos/**")
                    .notMatch("/testaa/1")
//                    .notMatch("/file/**")

//                    要执行的校验动作，这里是检查是否登录
                    .check(r-> StpUtil.checkLogin())
            ;
        })).addPathPatterns("/**");
    }
    //    进行跨域访问，要用下面两个方法，硬套就好了
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.addAllowedOriginPattern("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600)
                .exposedHeaders();
    }
}
